package com.dev.security.shiro;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.Map;

/**
 * shiro框架配置
 *
 * @ Author：across-cai
 * @ Time：2020/4/17 15:34
 * @ Motto：我只想做你的太阳
 */
@Configuration
public class ShiroConfiguration {

    //将自己的验证方式加入容器
    @Bean
    public MyShiroRealm myShiroRealm(){
        MyShiroRealm myShiroRealm = new MyShiroRealm();
        myShiroRealm.setCredentialsMatcher(new CredentialsMatcher());
        return myShiroRealm;
    }

    @Bean
    public DefaultWebSecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(myShiroRealm());

        return securityManager;
    }

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);

        Map<String, Filter> filterMap = shiroFilterFactoryBean.getFilters();
        //自定义Filter
        filterMap.put("authc",new LoginFilter());

        /**
         *  Filter 拦截那些请求可以配置
         *  Interceptor
         */
        Map<String, String> map = new HashMap<>();
        /**
         * key:路径 value：校验逻辑
         * authc：默认的一些过滤器 anon：不校验
         */

        //登出
        map.put("/logout","logout");
        //对所有用户认证
        map.put("/user/**","authc");
        map.put("/org/**","authc");
        map.put("/role/**","authc");
        map.put("/menu/**","authc");
        map.put("/log/**","authc");
        map.put("/index","authc");
        //map.put("/login.html","anon");
        //其他资源不拦截
        map.put("/**","anon");
        //进行绑定
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);

        //登录
        shiroFilterFactoryBean.setLoginUrl("/login.html");
        //首页
        shiroFilterFactoryBean.setSuccessUrl("/index");
        //错误的页面，认证不通过跳转
        shiroFilterFactoryBean.setUnauthorizedUrl("/error");

        return shiroFilterFactoryBean;
    }

}
